package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.FansAndFocusAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.FansAndLike;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: FansAndFocusActivity
 * @Description: 我的粉丝和我关注的页面
 * @Author: ljp
 * @CreateDate: 2018/10/11 15:28
 * @Version: 1.0
 */
public class FansAndFocusActivity extends BaseActivity {
    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recycler_fans_focus)
    RecyclerView recyclerFansFocus;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.default_text_view)
    TextView defaultTextView;
    @BindView(R.id.linear_layout)
    LinearLayout linearLayout;
    private String TAG = "FansAndFocusActivity";


    private String flag;//1 我的粉丝  0  我关注的  2我的隐友
    private FansAndFocusAdapter fansAndFocusAdapter;

    private ArrayList<FansAndLike.PageBean.ListBean> listBeans;
    private String token;
    private String deviceInfo;
    private int page;
    private String userId;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_fans_focus;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        flag = getIntent().getStringExtra("flag");
        initView();
    }

    /**
     * @return
     * @method
     * @description 布局控件实例化
     * @date: 2018/10/11 10:03
     * @author: ljp
     */
    private void initView() {
        page = 1;
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        MySelfInfoBean.ObjectBean mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        userId = mySeleInfo.getId();
        listBeans = new ArrayList<>();
        if (flag.equals("0")) {
            tvTitle.setText("我关注的");
        }else if(flag.equals("2")){
            tvTitle.setText("我的隐友");
        }
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                httpList();
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                httpList();
                smartRefresh.finishLoadMore(10000);
            }
        });
        fansAndFocusAdapter = new FansAndFocusAdapter(context, listBeans, R.layout.item_fans_focus,"");
        recyclerFansFocus.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerFansFocus.setAdapter(fansAndFocusAdapter);
        fansAndFocusAdapter.setItemOnClick(new FansAndFocusAdapter.ItemOnClick() {
            @Override
            public void setItemOnClick(int position, View view) {//跳往个人主页
            }
            @Override
            public void setStateOnClick(int position, View view) {//状态点击事件
                view.setEnabled(false);
                FansAndLike.PageBean.ListBean listBean = listBeans.get(position);
                setHttpLike(listBean,view);
            }
            @Override
            public void setIconOnClick(String userId, View view) {
                Log.i(TAG, "setIconOnClick: ---------"+userId);
                Intent intent = new Intent(activity, PersonalHomepageActivity.class);
                intent.putExtra("anchorId", userId);
                startActivity(intent);
            }
        });
        httpList();
    }

    /**
     * @return
     * @method
     * @description 关注取消关注
     * @date: 2018/10/24 11:56
     * @author: ljp
     */
    private void setHttpLike(FansAndLike.PageBean.ListBean listBean,View view) {
        MeInfoService.likeAndUnLike(token, deviceInfo, userId, listBean.getUserId()).subscribe(result -> {
            Log.i(TAG, "setHttpLike: --------" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                view.setEnabled(true);
                if (listBean.getState().equals("1")) {//1 未关注 2已经关注 3互相关注
                    if (flag.equals("0")) {//我关注列表
                        listBean.setState("2");
                    } else {//我的粉丝列表
                        listBean.setState("3");
                    }
                } else if (listBean.getState().equals("2")) {
                    listBean.setState("1");
                } else if (listBean.getState().equals("3")) {
                    listBean.setState("1");
                }
                fansAndFocusAdapter.notifyDataSetChanged();
                toast_MakeText(result.getMsg());
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                view.setEnabled(true);
                Utils.setToken(context);
            } else {
                view.setEnabled(true);
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            view.setEnabled(true);
            Log.i(TAG, "setHttpLike: ------" + throwable.toString());
        });
    }

    /**
     * @return
     * @method
     * @description 获取粉丝或关注列表
     * @date: 2018/10/23 15:21
     * @author: ljp
     */
    private void httpList() {
        if (flag.equals("0")) {//我关注的
            MeInfoService.myLikeList(token, deviceInfo, userId, page + "").subscribe(fansAndLike -> {
               // Log.i(TAG, "httpList: ---------" + fansAndLike.getPage().getList().toString());
                if (fansAndLike.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    int i = fansAndLike.getPage().getCount() / fansAndLike.getPage().getPageSize() +
                            (fansAndLike.getPage().getCount() % fansAndLike.getPage().getPageSize() == 0 ? 0 : 1);
                    //int i = postBean.getPage().getCount() % postBean.getPage().getPageSize();
                    if (i != 0 && page > i) {//判断是否是最后一页
                        smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                    } else {
                        if (page == 1) {
                            listBeans.clear();
                            smartRefresh.finishRefresh();
                        }
                        if(fansAndLike.getPage().getList() != null) {
                            linearLayout.setVisibility(View.GONE);
                            listBeans.addAll(fansAndLike.getPage().getList());
                            fansAndFocusAdapter.notifyDataSetChanged();
                            smartRefresh.setVisibility(View.VISIBLE);
                            smartRefresh.finishLoadMore();
                        }else {
                            smartRefresh.setVisibility(View.GONE);
                            linearLayout.setVisibility(View.VISIBLE);
                            defaultTextView.setText(getResources().getText(R.string.no_flows));
                        }
                    }
                } else if (fansAndLike.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                    removeAllActivity();
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    toast_MakeText(fansAndLike.getMsg());
                }
            }, throwable -> {
                Log.i(TAG, "httpList: ----" + throwable.toString());

            });
        } else if(flag.equals("1")){
            MeInfoService.myFansList(token, deviceInfo, userId, page + "").subscribe(fansAndLike -> {
                if (fansAndLike.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    int i = fansAndLike.getPage().getCount() / fansAndLike.getPage().getPageSize() +
                            (fansAndLike.getPage().getCount() % fansAndLike.getPage().getPageSize() == 0 ? 0 : 1);
                    //int i = postBean.getPage().getCount() % postBean.getPage().getPageSize();
                    if (i != 0 && page > i) {//判断是否是最后一页
                        smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                        // Log.i(TAG, "communityPostList: -------------postLists.size();--------" + postLists.size());
                    } else {
                        if (page == 1) {
                            listBeans.clear();
                            smartRefresh.finishRefresh();
                        }
                        if(fansAndLike.getPage().getList() != null) {
                            linearLayout.setVisibility(View.GONE);
                            listBeans.addAll(fansAndLike.getPage().getList());
                            fansAndFocusAdapter.notifyDataSetChanged();
                            smartRefresh.setVisibility(View.VISIBLE);
                            smartRefresh.finishLoadMore();
                        }else {
                            smartRefresh.setVisibility(View.GONE);
                            linearLayout.setVisibility(View.VISIBLE);
                            defaultTextView.setText(getResources().getText(R.string.no_fans));
                        }
                    }
                }
            }, throwable -> {
                Log.i(TAG, "httpList: ----" + throwable.toString());
            });
        }else {
            MeInfoService.myFriendsList(token, deviceInfo, userId, page + "").subscribe(fansAndLike -> {
                if (fansAndLike.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                    int i = fansAndLike.getPage().getCount() / fansAndLike.getPage().getPageSize() +
                            (fansAndLike.getPage().getCount() % fansAndLike.getPage().getPageSize() == 0 ? 0 : 1);
                    Log.i(TAG, "httpList: ----------"+fansAndLike.toString());
                    //int i = postBean.getPage().getCount() % postBean.getPage().getPageSize();
                    if (i != 0 && page > i) {//判断是否是最后一页
                        smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                        // Log.i(TAG, "communityPostList: -------------postLists.size();--------" + postLists.size());
                    } else {
                        if (page == 1) {
                            listBeans.clear();
                            smartRefresh.finishRefresh();
                        }
                        if(fansAndLike.getPage().getList() != null) {
                            linearLayout.setVisibility(View.GONE);
                            listBeans.addAll(fansAndLike.getPage().getList());
                            fansAndFocusAdapter.notifyDataSetChanged();
                            smartRefresh.setVisibility(View.VISIBLE);
                            smartRefresh.finishLoadMore();
                        }else {
                            smartRefresh.setVisibility(View.GONE);
                            linearLayout.setVisibility(View.VISIBLE);
                            defaultTextView.setText(getResources().getText(R.string.no_friends));
                        }
                    }
                }
            }, throwable -> {
                Log.i(TAG, "httpList: ----" + throwable.toString());
            });
        }
    }

    @OnClick(R.id.linear_back)
    public void onClick() {
        finish();
    }
}
